/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MODEL.DAO;

import MODEL.POJO.LoaiSanPhamPOJO;
import MODEL.UTIL.MySqlDataAccessHelper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author kijoo
 */
public class LoaiSanPhamDAO {
    public static ArrayList<LoaiSanPhamPOJO> LayDanhSachLoaiSanPham()
    {
        ArrayList<LoaiSanPhamPOJO> ds = new ArrayList<LoaiSanPhamPOJO>(); 
        try 
        {
            MySqlDataAccessHelper helper = new MySqlDataAccessHelper(); 
            helper.Open(); 
            String sql=String.format("SELECT * FROM LOAISANPHAM"); 
            ResultSet rs = helper.executeQuery(sql);
                while(rs.next())
                {
                    LoaiSanPhamPOJO lsp=new LoaiSanPhamPOJO();
                    lsp.setIdloaisanpham(rs.getString("idloaisanpham"));
                    lsp.setTenloaisanpham(rs.getString("tenloaisanpham"));
                    ds.add(lsp);
                }     
                helper.Close();  
        } catch (Exception ex) { System.out.println(ex.getMessage()); } 
        return ds;
    }
    
     public static int LaySoLuongSanPham(String idloaisanpham) {
      String sql = String.format("SELECT COUNT(*) AS SOLUONG FROM CHITIETSANPHAM WHERE IDLOAISANPHAM='%s'", idloaisanpham);
      int soLuong = -1;
      try {
         MySqlDataAccessHelper helper = new MySqlDataAccessHelper();
         helper.Open();
         ResultSet rs = helper.executeQuery(sql);
         if (rs.next()) {
            soLuong = rs.getInt("SoLuongTon");
         }
         helper.Close();
      } catch (SQLException ex) {
         System.out.println(ex.getMessage());
      }
      return soLuong;
   }

   public static int TinhSoLuongTrang(String idloaisanpham) {
      int soTrang;
      int soLuongSanPhamTrenTrang = 9;
      int soLuong = LoaiSanPhamDAO.LaySoLuongSanPham(idloaisanpham);
      soTrang = soLuong / soLuongSanPhamTrenTrang;
      if (soLuong % soLuongSanPhamTrenTrang != 0) {
         soTrang++;
      }
      return soTrang;
   }
    
   public static int SoSanPhamTheoTrang(String idloaisanpham, int trang) {
      int soLuongSanPhamToiDaTrenTrang = 9;
      int tongSoLuong = LoaiSanPhamDAO.LaySoLuongSanPham(idloaisanpham);
      int soTrang = tongSoLuong / soLuongSanPhamToiDaTrenTrang;
      if (tongSoLuong % soLuongSanPhamToiDaTrenTrang != 0) {
         soTrang++;
      }
      int soLuong;
      if (trang < soTrang) {
         soLuong = soLuongSanPhamToiDaTrenTrang;
      } else {
         soLuong = tongSoLuong % soLuongSanPhamToiDaTrenTrang;
      }
      return soLuong;
   }
}
